<template>
  <header class="nav-bar">
    <div class="logo" @click="goToHome">中国古代物理著作赏析</div>
    <nav class="nav-menu">
      <ul>
        <li><a href="#" @click.prevent="goToHome">首页</a></li>
        <li><a href="#" @click.prevent="goToAuthorsList">所有作者</a></li>
        <li v-if="!isLoggedIn"><a href="#" @click.prevent="goToLogin">登录</a></li>
        <li v-if="isLoggedIn" class="user-info">
          <span class="username" @mouseover="showOptions = true" @mouseleave="showOptions = false">
            {{ username }}
            <div v-if="showOptions" class="user-options">
              <div class="option" @click="goToProfile">个人中心</div>
              <div class="option" @click="handleLogout">退出</div>
            </div>
          </span>
        </li>
      </ul>
    </nav>
  </header>
</template>

<script>
export default {
  data() {
    return {
      isLoggedIn: false,
      username: '',
      showOptions: false
    };
  },
  methods: {
    goToHome() {
      this.$router.push({ name: 'home' });
    },
    goToAuthorsList() {
      this.$router.push({ name: 'AuthorsList' });
    },
    goToLogin() {
      this.$router.push({ name: 'login' });
    },
    goToProfile() {
      this.$router.push({ name: 'profile' }); // 路由跳转到个人中心
    },
    handleLogout() {
      // 清除登录信息
      localStorage.removeItem('token');
      localStorage.removeItem('username');
      localStorage.removeItem('isLoggedIn');
      // 重置组件状态
      this.isLoggedIn = false;
      this.username = '';
      // 跳转到登录页
      this.$router.push({ name: 'login' });
    }
  },
  created() {
    // 检查登录状态
    const token = localStorage.getItem('token');
    if (token) {
      this.isLoggedIn = true;
      this.username = localStorage.getItem('username');
    }
  }
};
</script>

<style scoped>
.nav-bar {
  background-color: #333;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}

.nav-menu ul {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-menu li {
  margin-left: 20px;
  display: flex;
  align-items: center;
}

.nav-menu a {
  color: white;
  text-decoration: none;
  font-size: 16px;
  padding: 8px 16px; /* 增加按钮宽度 */
  border-radius: 4px; /* 添加圆角 */
}

.nav-menu a:hover {
  text-decoration: underline;
  background-color: #555; /* 添加悬停背景色 */
}

.username {
  margin-left: 10px;
  color: white;
  font-size: 16px;
  position: relative; /* 为选项定位 */
}

.user-options {
  display: none; /* 默认隐藏选项 */
  position: absolute;
  top: 100%;
  left: 0;
  background-color: #333;
  padding: 5px 0;
  border-radius: 4px;
}

.option {
  padding: 10px 15px; /* 恢复默认内边距 */
  cursor: pointer;
  color: white;
  text-align: center; /* 文本居中 */
}

.option:hover {
  background-color: #555;
}

.user-info:hover .user-options {
  display: block; /* 鼠标悬停时显示选项 */
}
</style>